<?php

namespace app\common\service\arvato;

use app\common\model\jooj_member\ViewMemberIndex as ViewMemberIndexModel;
use app\common\model\oms\Staffs;
use app\common\model\oms\Store;
use app\common\service\ArvatoApiService;
use app\common\common\Constants;
use app\common\model\jooj_member\MemberIndex as MemberIndexModel;
use app\common\model\oms\Companies as CompanyModel;
use app\common\model\jooj_member\MemberVip as MemberVipModel;

/**
 * Description of arvato
 * 本类主要针对与arvato会员相关同步入队的功能
 * 
 * auther Leo.xie
 */
class ArvatoMemberService extends ArvatoBaseService {

    /**
     * 会员新增数据推送
     * @param type $JjUnid
     * @param type $companyCode
     */
    public function newMember($JjUnid, $companyCode = 'baodao') {

        if (strtolower($companyCode) != 'baodao') {
            return false;
        }

        $data = $this->getCompleteInfo(['jj_uni_id' => $JjUnid], $companyCode);
        $data['birthday'] = 0 != (int) $data['birthday'] ? $data['birthday'] : '';
        //新增会员的card_no是空的
        unset($data['card_no']);
        //加入到推送给arvato的队列中
        //$commonCurl = new CommonCurl();
        //$res = $commonCurl->curlSoa2('newMember', $data);
        $ArvatoApiService = new ArvatoApiService();
        $res = $ArvatoApiService->send(Constants::$pushArvartoFunc['newMember'], $data);
        return $res;
    }

    /**
     * 获取完整arvato会粉信息
     * @param type $condition
     * @param type $companyCode
     * @return type
     */
    public function getCompleteInfo($condition, $companyCode = 'baodao') {
        //新增的用户不确定是否有微信关系
        //所以先判断此用户信息
        //如果没有直接返回空的微信信息
        $companyId = $this->getCompanyIdByCompanyCode($companyCode);
        $viewMemberIndexModel = new ViewMemberIndexModel($companyId);
        $viewMember = $viewMemberIndexModel->getViewMemberIndexByCondition($condition);
        $viewMember['card_no'] = $viewMember['cardno'];
        $staffModel = new Staffs();
        $storesModel = new Store();
        $viewMember['emp_code'] = $staffModel->getStaffInfoByCondtion(['staff_id' => $viewMember['first_p']], 'staff_job_id')['staff_job_id'];
        $viewMember['shop_code'] = $storesModel->getStoreByCondition(['store_id' => $viewMember['first_store']], 'trusteeship_id')['trusteeship_id'];
        //来源的渠道
        $viewMember['channel_code'] = 'offline';
        if ($viewMember['come_from'] == 31 || $viewMember['come_from'] == 32) {
            $viewMember['channel_code'] = 'online';
        }
        unset($viewMember['come_from']);

        //活动编号，不知道怎么取【预留字段】
        $viewMember['campaign_code'] = '';

        //手机状态
        $viewMember['is_validate'] = ($viewMember['mobile_status'] == 1 ? 1 : 0);
        unset($viewMember['mobile_status']);

        //根据他当前会粉有没有openid判断来判断要不要取会粉信息
        $openId = isset($viewMember['account_code']) ? $viewMember['account_code'] : '';
        $wx_union_id = isset($viewMember['wx_union_id']) ? $viewMember['wx_union_id'] : '';

        switch (true) {
            case!empty($openId):
                $Fans = $this->getFans($openId, $companyId);
                break;
            case!empty($wx_union_id):
                $Fans = $this->getFansx($wx_union_id, $companyId);
                break;
            default :
                $Fans = [
                    'wx_avatar_url' => '',
                    'wx_openid' => '',
                    'wx_nick_name' => '',
                    'wx_sex' => '',
                    'wx_language' => '',
                    'wx_city' => '',
                    'wx_province' => '',
                    'wx_country' => '',
                    'wx_subscribe_time' => '',
                    'wx_unionid' => '',
                ];
                break;
        }

        $data = $this->MergeData($viewMember, $Fans);
        return $data;
    }

    /**
     * 合并成为acrm想要的data数据
     * @param type $viewMember
     * @param type $Fans
     */
    private function MergeData($viewMember, $Fans) {
        return $data = [
            'mobile' => $viewMember['mobile'] ?: null,
            'name' => $viewMember['name'] ?: null,
            'card_no' => $viewMember['card_no'] ?: null,
            'gender' => intval($viewMember['gender']),
            'birthday' => $viewMember['birthday'] ?: null,
            'shop_code' => $viewMember['shop_code'] ?: null,
            'emp_code' => $viewMember['emp_code'] ?: null,
            'channel_code' => $viewMember['channel_code'] ?: null,
            'campaign_code' => $viewMember['campaign_code'] ?: null,
            'is_validate' => intval($viewMember['is_validate']),
            'wx_avatar_url' => $Fans['wx_avatar_url'] ?: null,
            'wx_openid' => $Fans['wx_openid'] ?: null,
            'wx_nick_name' => $Fans['wx_nick_name'] ?: null,
            'wx_sex' => intval($Fans['wx_sex']),
            'wx_language' => $Fans['wx_language'] ?: null,
            'wx_city' => $Fans['wx_city'] ?: null,
            'wx_province' => $Fans['wx_province'] ?: null,
            'wx_country' => $Fans['wx_country'] ?: null,
            'wx_subscribe_time' => $Fans['wx_subscribe_time'] ?: null,
            'wx_unionid' => $Fans['wx_unionid'] ?: null,
        ];
    }

    /**
     * 绑定Openid的时候推送给arvato
     * @param type $openId
     * @param type $companyCode
     * @return boolean
     * @throws \Exception
     */
    public function bindOpenid($openId, $companyCode = "baodao") {

        if (strtolower($companyCode) != "baodao") {
            return false;
        }
        
        $newCardLev = '';

        try {

            $CompanyModel = new CompanyModel();
            $Company = $CompanyModel->getCompanyInfoByCondition('*', ['company_code' => "{$companyCode}"]);

            //绑定的时候，需要清理掉open_id那条的card_no
            $MemberIndexModel = new MemberIndexModel($Company['company_id']);
            $MemberVipModel = new MemberVipModel($Company['company_id']);

            $MemberIndex = $MemberIndexModel->getMemberIndexByOpenId($openId);
            if (isset($MemberIndex['cardno'])) {
                $MemberIndexModel->saveMemberIndexNull(['member_code' => "{$MemberIndex['member_code']}"], ['cardno' => null]);
            }

            $data = $this->getCompleteInfo(['account_code' => $openId], $companyCode);
            //把openId的那条的card_no给清理掉

            //将用户信息在arvato更新，已获取最新card_lev
            $ArvatoApiService = new ArvatoApiService();
            $res = $ArvatoApiService->send(Constants::$pushArvartoFunc['updateMember'], $data);
            if($res !== false){
                $newCardLev = $res['card_level'];
            }
            
            //从全部信息中抽离unset掉
            unset($data['name'], $data['gender'], $data['birthday'], $data['mobile'], $data['is_validate']);

            //再次推入绑定微信的队列【异步推送】
            $this->ArvatoPush($data, 'bindOpenid');
        } catch (\Exception $ex) {
            throw new \Exception($ex->getMessage());
        }
        
        return $newCardLev;
    }

    /**
     * 单独修改会员信息
     * @param type $JjUnid
     * @param type $companyCode
     * @throws \Exception
     */
    public function updateMemberInfo($JjUnid, $companyCode = "baodao") {

        if (strtolower($companyCode) != "baodao") {
            return false;
        }

        try {
            $data = $this->getCompleteInfo(['jj_uni_id' => $JjUnid], $companyCode);

            $update_data = [
                'card_no' => $data['card_no'],
                'name' => $data['name'],
                'gender' => $data['gender'],
                'birthday' => $data['birthday'],
                'mobile' => $data['mobile'],
                'is_validate' => $data['is_validate']
            ];
            //推入更新队列【异步推送】
            $this->ArvatoPush($update_data, 'updateMember');
        } catch (\Exception $ex) {
            throw new \Exception($ex->getMessage());
        }
    }
    

    /**
     * 单独修改会员信息(同步接口)
     * @param type $JjUnid
     * @param type $companyCode
     * @throws \Exception
     */
    public function updateMemberInfo_sync($JjUnid, $companyCode = "baodao") {

        if (strtolower($companyCode) != "baodao") {
            return false;
        }

        try {
            $data = $this->getCompleteInfo(['jj_uni_id' => $JjUnid], $companyCode);

            $update_data = [
                'card_no' => $data['card_no'],
                'name' => $data['name'],
                'gender' => $data['gender'],
                'birthday' => $data['birthday'],
                'mobile' => $data['mobile'],
                'is_validate' => $data['is_validate']
            ];
//            //推入更新队列【异步推送】
//            $this->ArvatoPush($update_data, 'updateMember');

            $ArvatoApiService = new ArvatoApiService();
            $res = $ArvatoApiService->send(Constants::$pushArvartoFunc['updateMember'], $update_data);
        } catch (\Exception $ex) {
            throw new \Exception($ex->getMessage());
        }

        return $res;
    }

}
